define(
	[
		'require',
		'apm/form_upload'
	],
	function(require) {
		var FormUploader = require('apm/form_upload');

		var Controller = Ember.Controller.extend({
			needs: ["businessCenter", "businessDetail"],

			business: Ember.computed.alias('controllers.businessDetail.model'),

			timePoint: Ember.computed.oneWay('controllers.businessDetail.timePoint'),

			isRealtimeMode: Ember.computed.oneWay('controllers.businessDetail.isRealtimeMode'),

			sequenceChartDisplayMode: Ember.computed.alias('controllers.businessDetail.sequenceChartDisplayMode'),

			isNodeListOpen: false,

			needRefreshNodes: true,

			alarmStartTime: '08:00:00',
			alarmEndTime: '17:00:00',

			nodeKeywordChange: Ember.observer("nodeKeyword", function() {
				var ctrl = this;
				this.requireNodes({
						appId: this.get("business.id"),
						keyWord: this.get('nodeKeyword') || ''
					})
					.then(function() {
						ctrl.set('needRefreshNodes', false);
					});
			}),

			//初始化时加载后台告警时间
			initOnloadTime: function(validTime, name) {
				var arr = validTime[name].split("-");
				this.set("alarmStartTime", arr[0]);
				this.set("alarmEndTime", arr[1]);
			},

			//删除数组指定一项
			findIndex: function(arr, val) {
				for (var i = 0; i < arr.length; i++) {
					if (arr[i] == val) return i;
				}
				return -1;
			},

			removeArrayItem: function(arr, val) {
				var index = this.findIndex(arr, val);
				if (index > -1) {
					arr.splice(index, 1);
				}
				return arr;
			},

			//去重
			arrayToWeight: function(arr) {
				arr = arr || [];
				var res = [];
				var json = {};
				for (var i = 0; i < arr.length; i++) {
					if (!json[arr[i]]) {
						res.push(arr[i]);
						json[arr[i]] = 1;
					}
				}
				return res;
			},

			defaultAlarmTime: function(validTime) {
				var ctrl = this;
				ctrl.set("validTimeReturn", validTime);
				for (var name in validTime) {
					switch (name) {
						case "1":
							$(".alarm-time-day span:eq(0)").addClass("active");
							ctrl.initOnloadTime(validTime, name);
							break;
						case "2":
							$(".alarm-time-day span:eq(1)").addClass("active");
							ctrl.initOnloadTime(validTime, name);
							break;
						case "3":
							$(".alarm-time-day span:eq(2)").addClass("active");
							ctrl.initOnloadTime(validTime, name);
							break;
						case "4":
							$(".alarm-time-day span:eq(3)").addClass("active");
							ctrl.initOnloadTime(validTime, name);
							break;
						case "5":
							$(".alarm-time-day span:eq(4)").addClass("active");
							ctrl.initOnloadTime(validTime, name);
							break;
						case "6":
							$(".alarm-time-day span:eq(5)").addClass("active");
							ctrl.initOnloadTime(validTime, name);
							break;
					}
				};

			},

			alarmTimeChange: Ember.observer("alarmStartTime", "alarmEndTime", function() {

				this.set("alarmTimeSlot", this.get("alarmStartTime") + " - " + this.get("alarmEndTime"));

			}),

			init: function() {
				this.set("cancelSet", true);
				if (overviewOrCenterSwitch == "business") {
					this.set("isShowSystemOrBusiness", false);
				} else {
					this.set("isShowSystemOrBusiness", true);
				}
				this.set("alarmTimeSlot", this.get("alarmStartTime") + " - " + this.get("alarmEndTime"));
			},

			businessIdChange: Ember.observer("business.id", function() {
				this.set('isNodeListOpen', false);
				this.set('needRefreshNodes', true);
				this.set('nodeKeyword', '');
			}),

			businessNodesChange: Ember.observer("business.id", "business.topoNodes", function() {
				if (!this.get("business")) {
					return;
				}

				var topoContent = {
					topoNodes: Ember.A(Ember.copy(this.get("business.topoNodes"), true) || []),
					relations: Ember.A(Ember.copy(this.get("business.relations"), true) || [])
				};
				this.set("expandedCluster", null);
				this.set("topoContent", topoContent);
				this.updateNodesPerformances();
			}),

			isRealtimeModeChange: Ember.observer("isRealtimeMode", "sequenceChartDisplayMode", function() {
				var bsView = Broada.getView("businessSequenceView");
				var chart1 = Broada.getView("businessDetailGaugeChart1");
				var chart2 = Broada.getView("businessDetailGaugeChart2");
				var chart3 = Broada.getView("businessDetailGaugeChart3");
				var chart4 = Broada.getView("businessDetailGaugeChart4");

				if (this.get("isRealtimeMode") || this.get("sequenceChartDisplayMode") == "detail") {
					return;
				}

				if (bsView && chart1 && chart2 && chart3 && chart4) {
					var bsViewChart = bsView.overviewChart;
					bsViewChart.disConnect(chart1.chart);
					bsViewChart.disConnect(chart2.chart);
					bsViewChart.disConnect(chart3.chart);
					bsViewChart.disConnect(chart4.chart);
				}
			}),

			topoScale: "100 %",

			isNodeUnSelected: Ember.computed("selectedNodes", function(key, value) {
				var len = this.get("selectedNodes.length");
				return len == null || len == 0;
			}),

			appApdexAtTimePoint: Ember.computed("business.performances", "timePoint", function(key, value) {
				var performance = this._getPerformance();
				if (overviewOrCenterSwitch == "business") {
					var apdex = performance && performance["business/score/apdex"];
				} else {
					var apdex = performance && performance["system/score/apdex"];
				}

				return apdex === undefined ? "-" : (apdex.toString().indexOf(".") == -1 ? (apdex += ".00") : (apdex.toString().substring(apdex.toString().indexOf(".")).length == 2 ? (apdex += "0") : apdex)) + "  [" + this.get("business").apdex_t + "]";
			}),

			appApdexAtTimePointText: Ember.computed("business.performances", "timePoint", function(key, value) {
				var performance = this._getPerformance();
				if (overviewOrCenterSwitch == "business") {
					var apdex = performance && performance["business/score/apdex"];
				} else {
					var apdex = performance && performance["system/score/apdex"];
				}

				if (apdex) {
					var status = parseFloat(apdex);
					var text = '';
					var statusMatching = [
						[1, '优秀'],
						[0.94, '良好'],
						[0.85, '一般'],
						[0.7, ' 差'],
						[0.5, '极差'],
						[0, '极差']
					]
					for (var i = 0; i < statusMatching.length; i++) {
						var item = statusMatching[i];
						if (status <= item[0]) {
							text = item[1];
						} else {
							return text;
						}
					}
				}
			}),

			appErrorAtTimePoint: Ember.computed("business.performances", "timePoint", function(key, value) {
				var performance = this._getPerformance();
				var error = performance && performance["system/error/count"];
				return error === undefined ? "-" : error;
			}),

			appRequestAtTimePoint: Ember.computed("business.performances", "timePoint", function(key, value) {
				var performance = this._getPerformance();
				var request = performance && performance["system/throughput/total"];
				return request === undefined ? "-" : request;
			}),

			appResponseTimeAtTimePoint: Ember.computed("business.performances", "timePoint", function(key, value) {
				var performance = this._getPerformance();
				var responseTime = performance && performance["system/response_time/avg"];
				return APM.util.indicatorFormatter("transform_time_ms")(responseTime);
			}),

			appSuccessRateAtTimePoint: Ember.computed("business.performances", "timePoint", function(key, value) {
				var performance = this._getPerformance();
				var error = performance && performance["system/success/rate"];
				return error === undefined ? "-" : error;
			}),

			appConcurrentUsersAtTimePoint: Ember.computed("business.performances", "timePoint", function(key, value) {
				var performance = this._getPerformance();
				var concurrentUsers = performance && performance["system/user/unique"];
				return concurrentUsers === undefined ? "-" : concurrentUsers;
			}),

			_getPerformance: function() {
				var performances = Ember.A(this.get("business.performances") || []);
				var timePoint = this.get("timePoint");
				var performance;
				if (!timePoint) {
					if (performances.length > 0) {
						performance = performances[performances.length - 1];
					}
				} else {
					performance = performances.findBy("timestamp", this.get("timePoint"));
				}
				return performance;
			},

			l4protocols: Ember.A([{
				displaytext: '请选择',
				value: ''
			}, {
				displaytext: 'tcp',
				value: 6
			}, {
				displaytext: 'udp',
				value: 17
			}]),

			topoMenusConfig: Ember.A([{
					name: "设置名称",
					cls: "icon-tags",
					code: "SET_NAME",
					accessBy: "1,3"
				}, {
					name: "设置名称",
					cls: "icon-tags",
					code: "SET_NAME",
					accessBy: "2"
				}, {
					name: "IP过滤",
					cls: "icon-search",
					code: "IP_FILTER",
					accessBy: "1,2"
				},
				// {
				// 	name: "配置L7层服务",
				// 	cls: "icon-cog",
				// 	code: "CONFIG_L7",
				// 	accessBy: "1,2"
				// },
				// {
				// 	name: "切换显示模式",
				// 	cls: "icon-th-large",
				// 	code: "DISPLAY MODE",
				// 	accessBy: "1,2"
				// },
				{
					name: "配置告警阈值",
					cls: "icon-wrench",
					code: "CONFIG_THRESHOLD",
					accessBy: "1,3"
				},
				// {
				// 	name: "设定SSL证书",
				// 	cls: "icon-wrench",
				// 	code: "CONFIG_SSL",
				// 	accessBy: "1,3"
				// },
				// {
				// 	name: "设置LUA",
				// 	cls: "icon-wrench",
				// 	code: "CONFIG_LUA",
				// 	accessBy: "1,3,2"
				// },
				// {
				// 	name: "导出协议样本包",
				// 	cls: "icon-download-alt",
				// 	code: "DOWNLOAD_PSP",
				// 	accessBy: "1,3"
				// },
				{
					name: "查找上级业务组件",
					cls: "icon-search",
					code: "QUERY_RELATION_NODE_LAST",
					accessBy: "1"
				},

				{
					name: "查找下级业务组件",
					cls: "icon-search",
					code: "QUERY_RELATION_NODE_NEXT",
					accessBy: "1"
				},
				// {
				// 	name: "查看详情",
				// 	cls: "icon-book",
				// 	code: "GOTO_DETAIL",
				// 	accessBy: "1,2,3"
				// },
				// {
				// 	name: "设置关键节点",
				// 	cls: "icon-tag",
				// 	code: "SET_KEYNODE",
				// 	accessBy: "1,2"
				// },
				{
					name: "删除业务组件",
					cls: "icon-remove",
					code: "DELETE_NODE",
					accessBy: "1,4"
				}, {
					name: "删除节点组",
					cls: "icon-remove",
					code: "DELETE_NODE",
					accessBy: "2"
				}, {
					name: "查看节点组",
					cls: "icon-info-sign",
					code: "SHOW_CLUSTER",
					accessBy: "2"
				}, {
					name: "脱离节点组",
					cls: "icon-minus-sign",
					code: "OUT_OF_CLUSTER",
					accessBy: "3"
				}, {
					name: "删除连线",
					cls: "icon-remove",
					code: "DELETE_RELATION",
					accessBy: "9" //连线菜单
				}
				// {
				// 	name: "设置",
				// 	cls: "icon-cog",
				// 	code: "CONFIG_RELATION",
				// 	accessBy: "9" //连线菜单
				// }
			]),

			selectImg: Ember.computed(function() {
				var imgAndName = [{
					"url": "/web/resource/img/topo/WebServices.jpg",
					"name": "网上服务"
				}, {
					"url": "/web/resource/img/topo/Counter.jpg",
					"name": "柜面"
				}, {
					"url": "/web/resource/img/topo/ATM.jpg",
					"name": "ATM"
				}, {
					"url": "/web/resource/img/topo/POS.jpg",
					"name": "POS"
				}, {
					"url": "/web/resource/img/topo/xindai.jpg",
					"name": "信贷"
				}, {
					"url": "/web/resource/img/topo/UnionPay.jpg",
					"name": "银联"
				}, {
					"url": "/web/resource/img/topo/payment.jpg",
					"name": "二代支付"
				}, {
					"url": "/web/resource/img/topo/VISA.jpg",
					"name": "VISA"
				}, {
					"url": "/web/resource/img/topo/MASTER_CARD.png",
					"name": "master\n card"
				}, {
					"url": "/web/resource/img/topo/Onlinebanking.jpg",
					"name": "网银"
				}, {
					"url": "/web/resource/img/topo/MobileBanking.jpg",
					"name": "手机银行"
				}, {
					"url": "/web/resource/img/topo/Alipay.jpg",
					"name": "支付宝"
				}, {
					"url": "/web/resource/img/topo/WeChatPayment.jpg",
					"name": "微信支付"
				}, {
					"url": "/web/resource/img/topo/qita.jpg",
					"name": "其他"
				}];
				return Ember.A(imgAndName);
			}),


			/*
				添加业务系统性能数据观察器, 业务系统性能数据改变后, 更新拓扑图性能数据
			*/
			addObserver4AppPerformances: function() {
				this.addObserver("business.performances", this, "updateNodesPerformances");
			},

			/*
				移除业务系统性能数据观察器
			*/
			removeObserver4AppPerformances: function() {
				this.removeObserver("business.performances", this, "updateNodesPerformances");
			},

			/*
				自动智能补全性能数据以填充图标, 按每分钟一条数据
				@param {array} performances 性能数组
				@param {nunber} tarLen 补全后的目标长度
				@param {date} endDate 结束时间
			*/
			performancesCompletion: function(performances, startDate, endDate) {
				return this.get("controllers.businessCenter").performancesCompletion(performances, startDate, endDate);
			},

			/*
				向服务端请求节点列表
			*/
			requireNodes: function(params) {
				var ctrl = this,
					appId = this.get("business.id");

				ctrl.set("nodes", Ember.A([{
					_displayName: "加载中..."
				}]));
				return ctrl.store.ajax("GET", "nodes", params)
					.then(function(response) {
						var nodes = Ember.A(response.nodes);
						nodes.forEach(function(node) {
							var html = '';
							if (node.createBy == 'manual') {
								html = '<b class="bold">[手动]</b> ';
							}
							html += node.name ? node.name : (node.ip + ':' + node.port);
							var title = 'IP:' + node.ip + ' 端口：' + node.port;
							node._title = new Ember.Handlebars.SafeString(title);
							node._displayName = new Ember.Handlebars.SafeString(html);
							node._displayFlow = APM.util.flowFormatter(node.flow);
						});
						ctrl.set("nodes", nodes);
					});
			},

			/*
				向服务端请求某一小时内的详细性能数据
			*/
			updateNodesPerformances: function() {
				var ctrl = this,
					business = this.get("business"),
					topoNodes = Ember.A(business.topoNodes || []),
					expandedCluster = this.get("expandedCluster"),
					nodeIds = [];

				topoNodes.forEach(function(node) {
					if (node.nodeType != 3) {
						nodeIds.push(node.id);
					}
				});

				if (expandedCluster) {
					nodeIds = Ember.A([].concat(nodeIds, expandedCluster.nodeIds));
				}

				var promise = this.requirePerformances(nodeIds);
				promise.then(function(response) {
					Broada.getView("businessDetailGaugeTopo").updatePerformances(response);
				});

				this.requireAppComparedPerformances();

				return promise;
			},

			updateClusterNodesPerformances: function(clusterNode, topoView) {
				var ctrl = this,
					nodeIds = Ember.A(clusterNode.nodeIds);

				var promise = this.requirePerformances(nodeIds);

				promise.then(function(response) {
					response[clusterNode.id] = clusterNode.performances;
					topoView.updatePerformances(response);
				});

				return promise;
			},

			requirePerformances: function(nodeIds) {
				var ctrl = this;
				var business = this.get("business");
				var appPfms = this.get("business.performances");
				var topoContent = this.get("topoContent");

				if (!(appPfms && appPfms.length > 0 && topoContent)) {
					return Ember.RSVP.reject("时序图没有数据");
				}

				if (nodeIds.length == 0) {
					if (Broada.getView("businessDetailGaugeTopo")) {
						Broada.getView("businessDetailGaugeTopo").zoomRestore();
					};

					return Ember.RSVP.reject("没有传入业务组件id");
				}

				var startDate, endDate;
				startDate = new Date(appPfms[0].timestamp);
				endDate = new Date(+startDate)
				endDate.setHours(endDate.getHours() + 1);

				//开发调试模式参数
				if (isLocalDebugModel) {
					startDate = new Date(1412132400000);
					endDate = new Date(+startDate)
					endDate.setHours(endDate.getHours() + 1);
				}

				return this.store.ajax("GET", "performances", {
						appId: business.id,
						nodeIds: nodeIds.join(),
						startDate: +startDate,
						endDate: +endDate
					})
					.then(function(response) {
						nodeIds.forEach(function(nodeId) {
							var performances = Ember.A(response[nodeId] || []);

							performances = ctrl.performancesCompletion(performances, startDate, endDate);

							response[nodeId] = performances;
						});

						business.topoNodes.forEach(function(node) {
							if (response[node.id]) {
								Ember.set(node, "performances", Ember.A(response[node.id]));
							}
						});

						return response;
					});
			},

			requireAppComparedPerformances: function() {
				var ctrl = this,
					appId = this.get("business.id"),
					appPfms = this.get("business.performances"),
					store = this.store;

				if (!(appPfms && appPfms.length > 0)) {
					return Ember.RSVP.reject("时序图没有数据");
				}

				var sDate1, eDate1, sDate2, eDate2;

				sDate1 = new Date(appPfms[0].timestamp);
				sDate1.setDate(sDate1.getDate() - 1);
				eDate1 = new Date(+sDate1);
				eDate1.setHours(eDate1.getHours() + 1);

				sDate2 = new Date(appPfms[0].timestamp);
				sDate2.setDate(sDate2.getDate() - 7);
				eDate2 = new Date(+sDate2);
				eDate2.setHours(eDate2.getHours() + 1);

				return Ember.RSVP.all([
						store.ajax("GET", "performances", {
							appIds: appId,
							startDate: +sDate1,
							endDate: +eDate1
						}),
						store.ajax("GET", "performances", {
							appIds: appId,
							startDate: +sDate2,
							endDate: +eDate2
						})
					])
					.then(function(response) {
						ctrl.set("appPerformances", [
							ctrl.performancesCompletion(Ember.A(response[1][appId] || []), sDate2, eDate2),
							ctrl.performancesCompletion(Ember.A(response[0][appId] || []), sDate1, eDate1),
							ctrl.get("business.performances")
						]);
					});
			},

			findRelationsByNode: function(nodeIds) {
				var business = this.get("business");
				return this.store.ajax("GET", "applications/" + business.id + "/topology/relations", {
					nodeIds: nodeIds.join()
				});
			},

			deleteTopoNodes: function(nodeDatas) {
				var business = this.get("business");
				var ids = Ember.A(nodeDatas).map(function(node) {
					return node.id;
				});
				return this.store.ajax("DELETE", "applications/" + business.id + "/topology/nodes", {
					ids: ids.join()
				});
			},

			setKeyNode: function(nodeId) {
				var business = this.get("business");
				return this.store.ajax("PUT", "nodes/keynode", {
					appId: business.id,
					nodeId: nodeId
				});
			},

			addOrUpdateTopoNodes: function(nodes) {
				var ctrl = this;
				var appId = this.get("business.id");
				var url = "applications/" + appId + "/" + overviewOrCenterSwitch + "/topology/nodes";

				return this.store.ajax("POST", url, nodes);
			},

			/*
				获取L7层协议下拉数据
			*/
			getL7OptionData: function(refresh) {
				var me = this;
				return this.store.ajax("GET", "protocols/L7").then(function(response) {
					if (response.protocols) {
						var arr = [{
							displaytext: '请选择',
							value: ''
						}];
						Ember.EnumerableUtils.forEach(response.protocols, function(item) {
							arr.push({
								displaytext: item.name,
								value: item.l7_proto,
								data: item
							})
						});
						me.set("l7Options", Ember.A(arr));
					}
				});
			},

			/*
				协议变动更新对应参数 功能暂时不要
			*/
			/*nodeFormProtocolChange: Ember.observer("nodeForm.protocol", function() {
				var ctrl = this, nodeForm = ctrl.get('nodeForm');

				if (!nodeForm.protocol) {
					ctrl.set('nodeForm.args', Ember.A([]));
					return ;
				}

				var protocolData = nodeForm.protocol.split(' ');
				this.store.ajax("GET", "configs/modulel7/argument/"+nodeForm.id, {l7_proto: protocolData[0], version:protocolData[1]})
				.then(function(response) {
					ctrl.set('nodeForm.args', Ember.A(response.result));
				});
			}),*/

			dialogButtons: {
				ok: {
					text: "确定",
					"class": "btn btn-primary",
					click: function() {
						var ctrl = this.get("controller");
						ctrl.send(this.get('dialogAction'), this);
					}
				},
				cancel: {
					text: "取消",
					"class": "btn",
					click: function() {
						this.closeDialog();
					}
				}
			},

			removeNodeFromCluster: function(node) {
				var ctrl = this;
				var topoView = Broada.getView("businessDetailGaugeTopo");
				return confirmDialog("是否将业务组件 " + node.name + " 脱离节点组?")
					.then(function() {
						var topoNodes = ctrl.get("business.topoNodes");
						var cluster = ctrl._findClusterOf(node);
						if (cluster) {
							var nodeIds = Ember.A([].concat(cluster.nodeIds));
							nodeIds.removeObject(node.id);

							return ctrl.addOrUpdateTopoNodes([{
									id: cluster.id,
									nodeIds: nodeIds
								}, {
									id: node.id,
									nodeType: 1
								}])
								.then(function() {
									cluster.nodeIds.removeObject(node.id);
									topoNodes.findBy("id", node.id).nodeType = 1;
									node.nodeType = 1;
									topoNodes.forEach(function(node) {
										if (node.nodeType == 2) {
											if (!node.nodeIds[0]) {

												ctrl.deleteTopoNodes([node])
													.then(function() {
														topoView.delNodes([node]);
														ctrl.get("business.topoNodes").removeObject(Ember.A(ctrl.get("business.topoNodes")).filterBy('id', node.id)[0]);
													});
											}

										}
									});
									return cluster;
								});
						} else {
							return Ember.RSVP.reject();
						}
					});
			},

			_findClusterOf: function(theNode) {
				var allNodes = this.get("business.topoNodes"),
					cluster;

				allNodes.forEach(function(node) {
					if (node.nodeType == 2) {
						Ember.A(node.nodeIds).forEach(function(nodeId) {
							if (nodeId == theNode.id) {
								cluster = node;
							}
						});
					}
				});

				return cluster;
			},

			expandCluster: function(data, topoView) {
				this.set("expandedCluster", data);
				topoView.expandCluster(data);
				this.updateClusterNodesPerformances(data, topoView);
			},

			reset: function() {
				this.set("topoScale", "100 %");
				this.set("isLinkNodeMode", false);
				this.set("topoContent", null);
				this.removeObserver4AppPerformances();
			},

			serviceNode: true,
			selectedSmallName: "选择节点图标",
			sourceIp: Ember.A(),
			actions: {
				cancelSourceIp: function() {
					var dialog = Broada.getView("businessDetailIPFilter");
					dialog.closeDialog();
				},
				editSourceIp: function() {
					var dialog = Broada.getView("businessDetailIPFilter"),
						sourceIp = this.get("sourceIp"),
						sourceIpTransmit = this.get("sourceIpTransmit"),
						sourceIpId = this.get("sourceIpId"),
						sourceIpList = $(".sourceIpList textarea").val();
					var sourceIpArr = sourceIpList.split("\n");
					var sourceStartAndEndIp;
					var ctrl = this;
					var bOk = true;
					var reg = /^(((\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\-(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5]))|((\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))$/

					for (var i = 0; i < sourceIpArr.length; i++) {
						if (sourceIpArr[i] == '') {
							sourceIpArr.splice(i, 1);
						};
					}
					if (sourceStartAndEndIp) {
						sourceStartAndEndIp.forEach(function(node) {
							sourceIpArr.push(node);
						});
					}
					if (sourceIpArr) {
						sourceIpArr.forEach(function(node) {
							if (!reg.test(node)) {
								bOk = false;
							}
						});
					}

					if (!bOk) {
						if (sourceIpList == '') {
							sourceIp.pushObject({
								id: sourceIpId,
								ip: sourceIpArr
							});
							$(".sourceIpList textarea").val(sourceIpList);
							return;
						}
						ctrl.set("nodeAddformTip", "IP输入不正确");
						return;
					}
					sourceIp.pushObject({
						id: sourceIpId,
						ip: sourceIpArr
					});
					var topoNodes = this.get("business.topoNodes");
					var nodeId = this.get("sourceIpId"),
						appId = this.get("business.id");
					topoNodes.forEach(function(node) {
						if (node.id == sourceIpId) {
							ctrl.store.ajax("PUT", "nodes/" + appId + "/" + nodeId + "/ips", {
								"filterIps": sourceIpArr
							});
							node.filterIps = sourceIpArr;
							sourceIp = node.filterIps.join("\n");
							$(".sourceIpList textarea").val(sourceIp);
						}
					});
					// this.set("sourceIpList",sourceIp);
					dialog.closeDialog();
				},
				selectIcon: function() {
					var selectIconOpen = this.get("selectIconOpen");
					if (!selectIconOpen) {
						this.set("selectIconOpen", true);
					} else {
						this.set("selectIconOpen", false);
					}

				},
				iSselectedImg: function(url, name) {
					this.set("selectedSmallName", name);
					this.set("selectedSmallIcon", url);
					this.set("isShowSmallImg", true)
				},

				labelCancel: function() {
					this.set("isNodeListOpen", false);
				},

				openNodesPanel: function() {
					var ctrl = this;
					this.set("selectedSmallName", "选择节点图标");
					this.set("isShowSmallImg", false);
					this.set("selectedNodes", null);
					this.set("isNodeListOpen", true);
					//if (this.get('needRefreshNodes')) {
						this.requireNodes({
								appId: this.get("business.id"),
								keyWord: this.get('nodeKeyword') || ''
							})
							.then(function() {
								ctrl.set('needRefreshNodes', false);
							});
					//}
				},

				addServiceNode: function() {
					this.set("isLabelSwitch", false);
					this.set("labelNode", false);
					this.set("serviceNode", true);
				},

				labelNode: function() {
					this.set("isLabelSwitch", true);
					this.set("nodeAddformTip", "");
					this.set("labelNode", true);
					this.set("serviceNode", false);
				},

				closeNodesPanel: function() {
					this.set("isNodeListOpen", false);
				},

				queryNode: function() {
					var ctrl = this;
					this.requireNodes({
							appId: this.get("business.id"),
							keyWord: this.get('nodeKeyword') || ''
						})
						.then(function() {
							ctrl.set('needRefreshNodes', false);
						});
				},

				setTopoDisplayMode: function() {
					var sizes = ["small", "full"];
					var curSizeIndex = this.get("curSizeIndex") || 0;
					Broada.getView("businessDetailGaugeTopo").setDisplayMode(sizes[curSizeIndex]);
					curSizeIndex++;
					if (curSizeIndex > 1) {
						curSizeIndex = 0;
					}
					this.set("curSizeIndex", curSizeIndex);
				},

				zoomIn: function() {
					var topoView = Broada.getView("businessDetailGaugeTopo");
					topoView.zoomIn();
				},

				zoomOut: function() {
					var topoView = Broada.getView("businessDetailGaugeTopo");
					topoView.zoomOut();
				},

				onTopoScaled: function(scaling) {
					this.set("topoScale", (scaling * 100).toFixed(0) + " %");
				},

				updateTopo: function() {
					var ctrl = this;
					var topoView = Broada.getView("businessDetailGaugeTopo");
					var topoJSON = topoView.toJSON();
					var topoNodes = this.get("business.topoNodes");
					var sourceIp = this.get("sourceIp");
					var appId = this.get("business.id");
					var filterIpsArr = [];

					if (topoJSON.relations.length == 0 && topoJSON.topoNodes.length == 0) {
						return;
					}
					topoJSON.topoNodes.forEach(function(node) {
						topoNodes.forEach(function(item) {
							if (node.id == item.id) {
								node.filterIps = item.filterIps;
							}
						});
					});

					this.store.ajax("POST", "applications/" + appId + "/topology", topoJSON)
						.then(function(response) {
							var nodesMap = {};
							Ember.A(response.nodes).forEach(function(node) {
								nodesMap[node.id] = node;
							});
							ctrl.set("business.relations", Ember.A(response.relations));
							ctrl.get("business.topoNodes").forEach(function(node) {
								if (nodesMap[node.id]) {
									node.id = nodesMap[node.id].id;
									node.x = nodesMap[node.id].x;
									node.y = nodesMap[node.id].y;
									node.size = nodesMap[node.id].size;
								}
							});
							ctrl.set("isSave", true);
							alertTip("保存成功", "info");
						});
				},

				resetTopo: function() {
					var topoView = Broada.getView("businessDetailGaugeTopo");
					topoView.zoomRestore();
					this.businessNodesChange();
				},

				openAddCustomNode: function() {
					this.getL7OptionData();
					this.set('nodeForm', {
						nodeType: 1
					});
					this.set('nodeForm', {
						protocol: ''
					});
					this.set("nodeAddformTip", "");
					Broada.getView("businessAddNoteToTopo").openDialog();
				},

				addCustomNodeToTopo: function(dialog) {
					var ctrl = this,
						appId = this.get("business.id"),
						nodeForm = this.get('nodeForm');


					if (!nodeForm.ip) return this.set("nodeAddformTip", "ip不能为空！");
					if (!/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/.test(nodeForm.ip)) return this.set("nodeAddformTip", "ip不符合规则！");
					if (!nodeForm.port) return this.set("nodeAddformTip", "端口不能为空！");
					if (!(/^\d+$/.test(nodeForm.port) && (nodeForm.port < 65536))) return this.set("nodeAddformTip", "端口不符合规则！");


					var name = nodeForm.name;
					if (Ember.isBlank(name)) {
						name = nodeForm.ip + ":" + nodeForm.port;
					}

					ctrl.send("addNodesToTopo", [{
						name: name,
						ip: nodeForm.ip,
						port: nodeForm.port,
						nodeType: 1,
						protocol: nodeForm.protocol,
						x: 5,
						y: 55,
						size: "large"
					}]);

					dialog.closeDialog();
				},

				//新建标签
				labelDetermine: function() {
					var ctrl = this;

					addlabelNodeArr = [];

					if (!ctrl.get("guageLabelName")) {
						alertTip("请输入标签名！");
						return;
					}
					if (ctrl.get("selectedSmallName") == "选择节点图标") {
						alertTip("请选择节点图标");
						return;
					}

					var addlabelNode = {
						"id": ctrl.get("guageLabelName"),
						"nodeType": 4,
						"picUrl": ctrl.get("selectedSmallIcon"),
						"name": ctrl.get("guageLabelName"),
						"x": 5 * 0,
						"y": 50 + 5 * 0,
						"size": "large"
					}


					addlabelNodeArr.push(addlabelNode);

					ctrl.addOrUpdateTopoNodes(addlabelNodeArr);

					var topoView = Broada.getView("businessDetailGaugeTopo");
					var auditedData = topoView.addNodes(addlabelNodeArr, Ember.A([]));

					var topoNodes = ctrl.get("business.topoNodes");
					var relations = ctrl.get("business.relations");

					Ember.A(auditedData.nodes).forEach(function(node) {
						topoNodes.push(node);
					});
					Ember.A(auditedData.relations).forEach(function(rel) {
						relations.push(rel);
					});

					alertTip("添加成功", "info");
					ctrl.set('isNodeListOpen', false);
					ctrl.set('isShowSmallImg', false);
					ctrl.set('guageLabelName', '');
				},

				addNodesToTopo: function(tmpNodes) {
					var ctrl = this;
					var selectedNodes = this.get("selectedNodes");
					if (!tmpNodes) {
						tmpNodes = [];

						selectedNodes && selectedNodes.forEach(function(node, i) {
							var name = node.name;
							if (Ember.isBlank(name)) {
								name = node.ip + ":" + node.port;
							}
							tmpNodes.push({
								"id": node.id,
								"nodeType": 1,
								"ip": node.ip,
								"port": node.port,
								"protocol": node.protocol,
								"name": name,
								"x": 5 * i,
								"y": 50 + 5 * i,
								"size": "large",
								"next": node.next,
								"previous": node.previous
							});
						});
					}

					if (tmpNodes.length == 0) {
						alertTip("请选择要添加的业务组件", "error");
						return;
					}

					this.addOrUpdateTopoNodes(tmpNodes)
						.then(function(response) {
							var nodeIds = Ember.A(response.topoNodes).mapBy("id");

							return ctrl.findRelationsByNode(nodeIds)
								.then(function(response2) {
									return {
										topoNodes: response.topoNodes,
										relations: response2.relations
									};
								})
						})
						.then(function(response) {
							var topoView = Broada.getView("businessDetailGaugeTopo");
							var auditedData = topoView.addNodes(response.topoNodes, Ember.A(response.relations));

							var topoNodes = ctrl.get("business.topoNodes");
							var relations = ctrl.get("business.relations");

							Ember.A(auditedData.nodes).forEach(function(node) {
								auditedData.relations.forEach(function(item) {
									if (node.id == item.from) {
										topoNodes.forEach(function(app) {
											if (item.to == app.id) {
												app.filterIps.push(node.ip);
											}
										});
									};
									if (node.id == item.to) {
										topoNodes.forEach(function(app) {
											if (item.from == app.id) {
												node.filterIps.push(app.ip);
											}
										});
									};
								});
								topoNodes.push(node);
							});

							ctrl.set("topoContent.topoNodes", topoNodes);
							Ember.A(auditedData.relations).forEach(function(rel) {
								relations.push(rel);
							});

							ctrl.send("closeNodesPanel");
							alertTip("添加成功", "info");
							ctrl.set('isNodeListOpen', false);
						});
				},

				deleteNodes: function() {
					var ctrl = this;
					var selectedNodes = this.get("selectedNodes");
					if (selectedNodes && selectedNodes.length > 0) {
						var manualNodes = selectedNodes.filterBy('createBy', 'manual');

						if (manualNodes.length == 0) {
							return alertDialog('只能删除手动添加的业务组件');
						}

						confirmDialog("是否删除选中的业务组件？").then(function() {
							ctrl.store.ajax("DELETE", "nodes/discovery", {
								nodeIds: Ember.A(manualNodes).mapBy('id').join(',')
							}).then(function(response) {
								ctrl.get('nodes').removeObjects(selectedNodes);
							});
						});
					} else {
						alertDialog("请选择要删除的业务组件", "error");
					}
				},

				queryRelationNode: function(serviceId, direction) {
					this.set("selectedNodes", null);
					this.set("isNodeListOpen", true);
					this.requireNodes({
						appId: this.get("business.id"),
						direction: direction,
						serviceId: serviceId
					});
				},

				topoMenuClick: function(menuCode, data, view, nodePanelsMap) {
					this.send("topoMenuHandler_" + menuCode, data, view, nodePanelsMap);
				},

				/*
					菜单按钮处理函数 设置节点名称
				*/
				topoMenuHandler_SET_NAME: function(data, topoView) {
					var dialog = Broada.getView("businessDetailGaugeSetNodeName");
					this.set("nodeAddformTip", "");
					this.set('nodeForm', {
						name: data.name,
						id: data.id
					});
					dialog.set('nodeModel', data);
					dialog.openDialog();
				},

				/*
					菜单按钮处理函数 配置L7层服务
				*/
				topoMenuHandler_CONFIG_L7: function(data, topoView) {
					var ctrl = this;
					var dialog = Broada.getView("businessDetailGaugeSetL7"),
						form = {
							id: data.id,
							protocol: data.protocol || data.autoDiscoveryProtocol || ''
						},
						promise = this.getL7OptionData();
					if (promise) {
						promise.then(function() {
							ctrl.set('nodeForm', form);
						});
					} else {
						this.set('nodeForm', form);
					};

					dialog.set('nodeModel', data);
					this.set("nodeAddformTip", "");
					dialog.openDialog();
				},
				/*
					菜单按钮处理函数 IP过滤弹框
				*/
				topoMenuHandler_IP_FILTER: function(data, topoView) {
					this.set("nodeAddformTip", "");
					this.set("sourceIpId", data.id);
					var dialog = Broada.getView("businessDetailIPFilter"),
						ctrl = this,
						sourceIp = '',
						topoNodes = this.get("business.topoNodes");
					topoNodes.forEach(function(node) {
						if (node.id == data.id) {
							var filterIps = ctrl.arrayToWeight(node.filterIps);
							sourceIp = filterIps.join("\n");
							$(".sourceIpList textarea").val(sourceIp);
						}
					});
					dialog.openDialog();
				},
				/*
					菜单按钮处理函数 IP过滤
				*/
				ByAddLinesSetIPfilter: function(data) {
					var topoNodes = this.get("business.topoNodes"),
						appId = this.get("business.id"),
						sourceIp = this.get("sourceIp"),
						isHaveIp = null;

					topoNodes.forEach(function(node) {
						data.forEach(function(item) {
							if (node.id == item.id) {
								if (item.from instanceof Array) {
									item.from.forEach(function(app) {
										node.filterIps.push(app);
									});
								} else {
									if (node.filterIps == null) {
										node.filterIps = [];
									}
									node.filterIps.forEach(function(app) {
										if (app == item.from) {
											isHaveIp = true;
										} else {
											isHaveIp = false;
										}
									});
									if (!isHaveIp) {
										node.filterIps.push(item.from);
									}
								}
							}
						});
					});
				},

				/*
					菜单按钮处理函数 切换显示模式
				*/
				topoMenuHandler_DISPLAY_MODE: function(data, topoView) {
					topoView.changeDisplayModeOf(data);
				},

				/*
					菜单按钮处理函数 配置告警阈值
				*/
				topoMenuHandler_CONFIG_THRESHOLD: function(data, topoView) {
					var dialog = Broada.getView("businessConfigThresholdView");
					dialog.set("targetResource", {
						targetId: data.id,
						targetName: data.name
					});
					dialog.requireThreshold(data.id);
					this.defaultAlarmTime();
					dialog.openDialog();
				},

				/*
					菜单按钮处理函数 设置关键节点
				*/
				topoMenuHandler_SET_KEYNODE: function(data, topoView) {
					var ctrl = this;
					confirmDialog("是否设置当前业务组件为关键业务组件?")
						.then(function() {
							return ctrl.setKeyNode(data.id);
						});
				},

				/*
					菜单按钮处理函数 查找上级业务组件
				*/
				topoMenuHandler_QUERY_RELATION_NODE_LAST: function(data, topoView) {
					this.send("queryRelationNode", data.id, "last");
				},
				/*
					菜单按钮处理函数 查找下级业务组件
				*/
				topoMenuHandler_QUERY_RELATION_NODE_NEXT: function(data, topoView) {
					this.send("queryRelationNode", data.id, "next");
				},
				/*
					菜单按钮处理函数 跳转到节点详情
				*/
				topoMenuHandler_GOTO_DETAIL: function(data, topoView) {
					this.transitionToRoute("business.detail.nodedetail.overview", this.get("business"), data);
				},
				/*
					菜单按钮处理函数 查看节点组
				*/
				topoMenuHandler_SHOW_CLUSTER: function(data, topoView) {
					this.expandCluster(data, topoView);
				},
				/*
					菜单按钮处理函数 删除节点
				*/
				topoMenuHandler_DELETE_NODE: function(data, topoView) {
					var ctrl = this,
						topoNodes = this.get("business.topoNodes"),
						relations = this.get("business.relations"),
						appId = this.get("business.id");
					var nodeTypeText = data.nodeType === 2 ? "节点组" : "业务组件";
					confirmDialog("是否删除" + nodeTypeText + " " + (data.name || (data.ip + ':' + data.port)) + " ?")
						.then(function() {
							return ctrl.deleteTopoNodes([data]);
						})
						.then(function() {

							topoView.delNodes([data]);
							ctrl.get("business.topoNodes").removeObject(Ember.A(ctrl.get("business.topoNodes")).filterBy('id', data.id)[0]);


							var delBeforeTopoNodes = ctrl.get("delBeforeTopoNodes"),
								delBeforeTopoLines = ctrl.get("delBeforeTopoLines");
							var lines = delBeforeTopoLines[0].data;

							if (data.id == lines.from) {
								var toNode = Ember.A(delBeforeTopoNodes).filterBy('id', lines.to),
									fromNode = Ember.A(delBeforeTopoNodes).filterBy('id', lines.from);
								if (!toNode[0].filterIps) {
									return;
								}
								var nodeIds = fromNode[0].nodeIds,
									filterIps = null;

								if (fromNode[0].nodeIds[0] ? true : false) {
									for (var i = 0; i < nodeIds.length; i++) {
										filterIps = ctrl.removeArrayItem(nodeIds, nodeIds[i]);
										i--;
									};
									ctrl.store.ajax("PUT", "nodes/" + appId + "/" + (lines.to) + "/ips", {
										"filterIps": filterIps
									});
									topoNodes.forEach(function(node) {
										if (node.id == lines.to) {
											node.filterIps = filterIps;
										}
									});

								} else {
									for (var i = 0; i < toNode[0].filterIps.length; i++) {
										if (toNode[0].filterIps[i] == data.ip) {
											toNode[0].filterIps.splice(i, 1);
											i--;
										}
									};
									ctrl.store.ajax("PUT", "nodes/" + appId + "/" + (lines.to) + "/ips", {
										"filterIps": toNode[0].filterIps
									});
								};



							}
							// if(data.id == lines.to){
							// 	var node =  Ember.A(delBeforeTopoNodes).filterBy('id', lines.from);
							// 	for(var i=0;i<node[0].filterIps.length;i++){
							// 		if(node[0].filterIps[i] == data.ip){
							// 			 node[0].filterIps.splice(i,1);
							// 			 ctrl.store.ajax("PUT", "nodes/"+appId+"/"+(lines.from)+"/ips",{"filterIps":node[0].filterIps[i]});
							// 						 i--;
							// 		}
							// 	};
							// }
							alertTip("删除成功", "info");
						});

				},
				/*
					菜单按钮处理函数 脱离节点组
				*/
				topoMenuHandler_OUT_OF_CLUSTER: function(data, topoView) {

					this.removeNodeFromCluster(data)
						.then(function(cluster) {
							topoView.removeNodeFromCluster(data);
							topoView.updateHeader(cluster);
						});


				},
				/*
					菜单按钮处理函数 删除连线
				*/
				topoMenuHandler_DELETE_RELATION: function(data, topoView) {
					topoView.removeLinkLine(data);
					var topoNodes = this.get("business.topoNodes"),
						ctrl = this,
						appId = this.get("business.id"),
						toNodeIP = topoNodes.findBy("id", data.from).ip,
						topoContent = this.get("topoContent");

					var topoView = Broada.getView("businessDetailGaugeTopo");
					var topoJSON = topoView.toJSON();

					this.store.ajax("POST", "applications/" + appId + "/topology", topoJSON)
						.then(function(response) {
							ctrl.set("business.relations", Ember.A(response.relations));
						});
					topoNodes.forEach(function(node) {
						if (node.id == data.to) {
							if (!node.nodeIds[0]) {
								var item = topoNodes.filterBy("id", data.from);
								var newArr = item[0].nodeIds.concat(node.filterIps);
								for (var i = 0; i < node.filterIps.length; i++) {
									for (var j = 0; j < (item[0].nodeIds.length); j++) {
										var newIp = topoNodes.filterBy("id", item[0].nodeIds[j])[0].ip;
										if (node.filterIps[i] == newIp) {
											node.filterIps.splice(i, 1);
										}
									}
								};
								return;
							};
							for (var i = 0; i < node.filterIps.length; i++) {
								if (node.filterIps[i] == toNodeIP) {
									node.filterIps.splice(i, 1);
									ctrl.store.ajax("PUT", "nodes/" + appId + "/" + (node.id) + "/ips", {
										"filterIps": node.filterIps[i]
									});
									i--;
								};
							}
						}
					});
				},

				/*
					菜单按钮处理函数 添加连线的同时保存到后台
				 */
				saveLine: function(toJSON) {
					var ctrl = this,
						topoNodes = this.get("business.topoNodes");

					toJSON.topoNodes.forEach(function(node) {
						if (!node.nodeIds) {
							topoNodes.forEach(function(item) {
								if (node.id == item.id) {
									item.filterIps = ctrl.arrayToWeight(item.filterIps)
									node.filterIps = item.filterIps;
								}
							});
						}
					});
					var appId = this.get("business.id");
					this.store.ajax("POST", "applications/" + appId + "/topology", toJSON)
						.then(function(response) {
							ctrl.set("business.relations", Ember.A(response.relations));
						});
				},

				/*
					菜单按钮处理函数 配置连线
				*/
				topoMenuHandler_CONFIG_RELATION: function(data, topoView) {},

				/*
					设置业务组件名称
				*/
				setNodeName: function(dialog) {
					var ctrl = this;
					var form = this.get('nodeForm'),
						nodeModel = dialog.get('nodeModel');

					if ($.trim(form.name) == '') return this.set("nodeAddformTip", "业务组件名称不能为空！");

					this.store.ajax("PUT", "nodes/" + form.id, {
							name: form.name
						})
						.then(function(response) {
							Ember.set(nodeModel, 'name', form.name);
							var topoContent = ctrl.get("topoContent");
							topoContent.topoNodes.forEach(function(node) {
								if (node.id == nodeModel.id) {
									node.name = nodeModel.name;
								}
							});

							var topoNodes = ctrl.get("business.topoNodes");
							topoNodes.forEach(function(node) {
								if (node.id == nodeModel.id) {
									node.name = nodeModel.name;
								}
							});

							Broada.getView("businessDetailGaugeTopo").updateNodeName(nodeModel);
							alertTip("保存成功！", "info");
							dialog.closeDialog();
						});
				},

				/*
					菜单按钮处理函数 删除节点并带删除IP
				*/
				delNodesTodelIp: function(lines, nodes) {
					this.set("delBeforeTopoNodes", nodes);
					this.set("delBeforeTopoLines", lines);

				},

				/*
					设置L7协议
				*/
				setNodeL7: function(dialog) {
					var protocolName = this.get("selectObject") ? this.get("selectObject").displaytext : '';
					var form = this.get('nodeForm'),
						nodeModel = dialog.get('nodeModel');

					if (form.protocol == '') return this.set("nodeAddformTip", "请选择L7服务！");

					this.store.ajax("PUT", "nodes/protocol", {
						service_id: form.id,
						l7_proto: form.protocol
					}).then(function(response) {
						alertTip("保存成功！", "info");
						Ember.set(nodeModel, 'protocol', form.protocol);
						Ember.set(nodeModel, 'protocolName', protocolName);
						if (response && response.node) {
							Ember.set(nodeModel, 'iconUrl', response.node.iconUrl);
							Broada.getView("businessDetailGaugeTopo").updateNodeIcon(nodeModel);
						}
						dialog.closeDialog();
					});
				},

				onDropNodeToNode: function(draggingNode, droppingNode, view) {
					var ctrl = this;
					var appId = this.get("business.id");

					var protocolA = draggingNode.protocol > 0 ? draggingNode.protocol : draggingNode.autoDiscoveryProtocol;
					var protocolB = droppingNode.protocol > 0 ? droppingNode.protocol : droppingNode.autoDiscoveryProtocol;

					if (draggingNode.nodeType === 4) {
						return;
					};
					if (droppingNode.nodeType === 1) {
						// if(protocolA != protocolB) {
						// 	alertDialog("不同服务的业务组件不能组成集群.");
						// 	return;
						// }
						ctrl.set("addClusterformTip", null);
						var addClusterView = Broada.getView("businessDetailGaugeAddNodeToNewCluster");
						addClusterView.openDialog();
						addClusterView.draggingNode = draggingNode;
						addClusterView.droppingNode = droppingNode;
						addClusterView.topoView = view;
					} else {
						// if(protocolA != protocolB) {
						// 	alertDialog("不同服务的业务组件不能组成集群.");
						// 	return;
						// }
						confirmDialog("是否将业务组件 " + draggingNode.name + " 加入节点组?")
							.then(function() {
								return ctrl.addOrUpdateTopoNodes([{
									"id": droppingNode.id,
									"nodeIds": [].concat(droppingNode.nodeIds, draggingNode.id)
								}, {
									id: draggingNode.id,
									nodeType: 3
								}]);
							})
							.then(function(response) {
								var topoNodes = ctrl.get("business.topoNodes");
								droppingNode = topoNodes.findBy("id", droppingNode.id);
								draggingNode.nodeType = 3;

								topoNodes.findBy("id", droppingNode.id).nodeIds.push(draggingNode.id);
								topoNodes.findBy("id", draggingNode.id).nodeType = 3;

								view.addNodeToCluster(draggingNode, droppingNode);
								droppingNode.iconUrl = "/web/resource/img/topo/node.png";
								view.updateHeader(droppingNode);
							});
					}
				},

				onNodeStackClick: function(data, view) {
					this.expandCluster(data, view);
				},

				onNodePfmsClick: function(data, dataKey, view) {
					var ctrl = this;
					switch (dataKey) {
						case "error":
							setTimeout(function() {
								ctrl.transitionToRoute("business.detail.nodedetail.errorcode", ctrl.get("business"), data);
							});
							break;
					}
				},

				addNodeToNewCluster: function(dialog) {
					var ctrl = this;
					var draggingNode = dialog.draggingNode;
					var droppingNode = dialog.droppingNode;
					var topoView = dialog.topoView;
					var name = ctrl.get("tempClusterName");

					if (name == "") {
						ctrl.set("addClusterformTip", "节点组名称不能为空");
						return;
					}
					ctrl.set("addClusterformTip", null);

					dialog.draggingNode = null;
					dialog.droppingNode = null;
					dialog.topoView = null;

					return ctrl.addOrUpdateTopoNodes([{
							"nodeType": 2,
							"name": ctrl.get("tempClusterName"),
							"x": droppingNode.x,
							"y": droppingNode.y,
							"size": droppingNode.size,
							"nodeIds": [
								draggingNode.id,
								droppingNode.id
							]
						}, {
							id: draggingNode.id,
							nodeType: 3
						}, {
							id: droppingNode.id,
							nodeType: 3
						}, ])
						.then(function(response) {
							var newCluster = response.topoNodes[0];
							var topoNodes = ctrl.get("business.topoNodes");

							topoNodes.pushObject(newCluster);
							draggingNode.nodeType = 3;
							droppingNode.nodeType = 3;
							topoNodes.findBy("id", droppingNode.id).nodeType = 3;
							topoNodes.findBy("id", draggingNode.id).nodeType = 3;

							topoNodes.forEach(function(node) {
								if (node.id == newCluster.id) {
									node.iconUrl = "/web/resource/img/topo/node.png";
								};
							});
							dialog.closeDialog();
							ctrl.set("tempClusterName", "");

							topoView.addNodes([newCluster], []);

							topoView.addNodeToCluster(draggingNode, newCluster);
							topoView.addNodeToCluster(droppingNode, newCluster);
						});
				},

				setRelations: function() {
					var isLinkNodeMode = this.get("isLinkNodeMode"),
						topoView = Broada.getView("businessDetailGaugeTopo");

					topoView.setLinkNodeMode(!isLinkNodeMode);
					this.set("isLinkNodeMode", !isLinkNodeMode);
				},

				selectRelationNode: function(node) {
					if (!node.id) {
						return;
					}

					this.set("selectedNodes", Ember.A([node]));
					this.get("nodes").forEach(function(node) {
						Ember.set(node, "isSelected", false);
					});
					Ember.set(node, "isSelected", true);
				}
			}
		});

		/*
			设置节点SSL证书功能扩展
		*/
		Controller.reopen({
			sslTypes: Ember.A([{
				displaytext: "RSA证书",
				value: "RSA"
			}]),

			actions: {
				/*
					菜单按钮处理函数 设定SSL证书
				*/
				topoMenuHandler_CONFIG_SSL: function(data, topoView) {
					var ctrl = this;
					var dialog = Broada.getView("businessNodeSsl");
					this.set("nodeSslformTip", "");
					this.set('nodeForm', {
						ssltype: data.ssltype,
						sslpwd: data.sslpwd
					});
					dialog.set('nodeModel', data);

					this.store.ajax("GET", "nodes/ssl", {
							serviceId: data.id
						})
						.then(function(response) {
							ctrl.set("hasNodeSSL", !!response.result);
							dialog.openDialog();
						});
				},
				/*
					设定SSL证书
				*/
				setNodeSsl: function(dialog) {
					var $form = $("#businessNodeSslForm"),
						formData = this.get('nodeForm'),
						nodeModel = dialog.get('nodeModel'),
						isBlank = Ember.isBlank;

					if (isBlank(formData.ssltype)) {
						return this.set("nodeSslformTip", "证书类型不能为空");
					}
					var formUploader = new FormUploader($form[0], {
						action: ADAPTER_URL + "/nodes/ssl",
						params: {
							serviceId: nodeModel.id,
							sslType: formData.ssltype,
							sslPwd: formData.sslpwd,
							token: $.cookie("token")
						}
					});
					formUploader.submit()
						.then(function(response) {
							dialog.closeDialog();
						});
				},

				/*
					删除已设定的SSL证书
				*/
				deleteNodeSsl: function() {
					var ctrl = this,
						dialog = Broada.getView("businessNodeSsl");
					this.store.ajax("DELETE", "nodes/ssl", {
							serviceId: dialog.get("nodeModel.id")
						})
						.then(function() {
							ctrl.set("hasNodeSSL", false);
							ctrl.set("nodeSslformTip", "证书已删除");
						});
				},

				resetNodeSsl: function() {
					this.set("hasNodeSSL", false);
				}
			}
		});
		/*
			设置LUA功能扩展
		*/
		Controller.reopen({
			actions: {
				/*
					菜单按钮处理函数 设置SSL证书
				*/
				topoMenuHandler_CONFIG_LUA: function(data, topoView) {
					var ctrl = this;
					var dialog = Broada.getView("businessNodeLua");
					ctrl.set("nodeLuaformTip", null);
					dialog.set('nodeModel', data);

					this.store.ajax("GET", "nodes/lua", {
							serviceId: data.id
						})
						.then(function(response) {
							ctrl.set('nodeForm', {
								lua: response.result.lua
							});
							dialog.openDialog();
						});
				},
				/*
					设置LUA
				*/
				setLua: function(dialog) {
					var ctrl = this,
						formData = this.get('nodeForm'),
						nodeModel = dialog.get('nodeModel');

					this.store.ajax("PUT", "nodes/lua", {
							serviceId: nodeModel.id,
							lua: formData.lua
						})
						.then(function(response) {
							if (response.status == "invalid") {
								ctrl.set("nodeLuaformTip", response.message);
							} else {
								alertTip("保存成功！", "info");
								dialog.closeDialog();
							}
						});
				}
			}
		});
		/*
			导出协议采样包
		*/
		Controller.reopen({
			specimenTimes: Ember.A([{
				displaytext: "3分钟",
				value: 3
			}, {
				displaytext: "15分钟",
				value: 15
			}, {
				displaytext: "1小时",
				value: 60
			}, {
				displaytext: "1天",
				value: 1440
			}, {
				displaytext: "自定义",
				value: null
			}]),

			downloadPSPURL: "about: blank",

			actions: {

				/*
					菜单按钮处理函数 导出协议采样包
				*/
				topoMenuHandler_DOWNLOAD_PSP: function(data, topoView) {
					var dialog = Broada.getView("businessNodeSpecimen");
					this.set('nodeForm', {
						time: 5
					});
					dialog.set('nodeModel', data);
					dialog.openDialog();
				},
				/*
					导出协议采样包
				*/
				downloadPSP: function(dialog) {
					var ctrl = this,
						formData = this.get('nodeForm'),
						nodeModel = dialog.get('nodeModel');

					var params = {
						serviceId: nodeModel.id
					};

					var time = parseInt(formData.time, 10);
					if (isNaN(time) || time < 0) {
						params.time = 1;
					} else {
						params.time = time;
					}

					if (isLocalDebugModel) {
						params = undefined;
					}

					this.store.ajax("GET", "nodes/downloadPSP", params)
						.then(function(response) {
							dialog.closeDialog();
						});
				},

				editApplication: function() {
					var view = Broada.getView("businessDetailGaugeSetNodeName");
					this.send("setNodeName", view);
				}
			}
		});

		APM.BusinessDetailGaugeController = Controller;

		return Controller;
	}
);